package com.zq.learn.akka.classic;

import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;

/**
 * 响应Actor
 *
 * @author ZhangQi
 * @date 2020/3/13
 */
public class CGreeterBot extends AbstractActor {
  private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

  //访问最大数
  private final int max;
  //访问次数
  private int greetingCounter;

  public static final class CGreeted{
    public final String whom;

    public CGreeted(String whom) {
      this.whom = whom;
    }
  }

  /**
   * 构造
   * @param max
   */
  public CGreeterBot(Integer max) {
    this.max = max;
  }

  /**
   * 对外开放赋值方法
   * @param max
   * @return
   */
  public static Props props(Integer max) {
    return Props.create(CGreeterBot.class, () -> new CGreeterBot(max));
  }


  /**
   * 接收方法（重写）
   *
   * @return
   */
  @Override public Receive createReceive() {
    return receiveBuilder().match(CGreeted.class,greeted->{
      greetingCounter++;
      log.info("Greeting {} for {}",greetingCounter,greeted.whom);
      if (greetingCounter<max){
        //推送消息
        getSender().tell(new CGreeter.CGreet("Lime"),getSelf());
      }
    }).build();
  }

}
